var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');
let multer  = require('multer');

// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views')); //指明项目里面模板引擎的位置放在views目录
app.set('view engine', 'ejs');  //当前项目可以通过res.render来去渲染一个ejs模板

//配置控制台打印日志的中间件
app.use(logger('dev'));

//中间件的安装 body-parser  req.body获取到非地址栏里面的数据
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//multer中间件的配置(1.可以获取上传图片req.files  2.req.body可以获取非地址栏的数据)
//通过multer实现上传图片的不同分发目录
// let upload = multer({dest:path.join(__dirname,"public","upload")})

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    //如果接口中存在reg或者user，那么我就上传到/upload/user文件夹中
    if(req.url.indexOf("user")!==-1 || req.url.indexOf("reg")!==-1){
      cb(null, path.join(__dirname,"public","upload","user"))
    }else if(req.url.indexOf("banner") !== -1){
      cb(null, path.join(__dirname,"public","upload","banner"))
    }else{
      cb(null, path.join(__dirname,"public","upload","product"))
    }
  }
})
let upload = multer({ storage: storage })
app.use(upload.any())




//多目录的静态资源托管
app.use(express.static(path.join(__dirname, 'public',"template")));
app.use("/admin",express.static(path.join(__dirname, 'public',"admin")));
app.use(express.static(path.join(__dirname,"public")))


// 用户的接口的响应
app.all("/api/*",require("./routes/api/params")) //处理api下发出的所有的接口的公共参数
app.use('/api/reg', require('./routes/api/reg'));
app.use('/api/login', require('./routes/api/login'));
app.use('/api/goods', require('./routes/api/goods'));

app.use('/api/user', require('./routes/api/user'));
app.use('/api/logout', require('./routes/api/logout')); //session  delete req.session[key]





// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);

  //如果上面的接口不存在或者静态资源不存在，就会走下面的错误处理.....
  if(req.url.includes("/api")){ //说明是用户接口不存在
    res.send({err:1,msg:"用户端接口不存在..."})
  }else if(req.url.includes("/admin")){ //说明是管理端接口不存在
    res.render('error')
  }else{ //静态资源不存在
    res.sendFile(path.join(__dirname,"public","template","404.html"))
  }
});

module.exports = app;
